<script setup lang="ts">
import { ref, reactive } from "vue"
import web3 from "web3"
import mButton from "@/components/m-button.vue"
import mPopup from "@/components/m-popup.vue"

const openData = ref(false)
const txParams = reactive({
    form: "",
    to: '',
    value: '0.1',
})

async function sendEth(fromAddress: string, toAddress: string, amountInEther: number) {
    try {
        // 获取用户当前的 ETH 余额
        const balance = await window.ethereum.request({ method: 'eth_getBalance', params: [fromAddress, 'latest'] });
        const balanceInEther = web3.utils.fromWei(balance, 'ether');
        console.log(`Current balance of ${fromAddress}: ${balanceInEther} ETH`);

        // 检查余额是否足够支付交易费用和转账金额
        if (Number(balanceInEther) < amountInEther) {
            uni.showToast({
                title: '余额不足',
                icon: 'none'
            })
            return
        }

        // 构建交易参数
        const transactionParameters = {
            from: fromAddress,
            to: toAddress,
            value: web3.utils.toWei(amountInEther.toString(), 'ether'),
            gas: 21000, // 标准 ETH 转账所需的 gas
        };

        // 发送交易
        const transactionHash = await window.ethereum.request({
            method: 'eth_sendTransaction',
            params: [transactionParameters],
        });
        uni.showToast({
            title: `发送成功,hash:${transactionHash}`,
            icon: 'none'
        })
        console.log(`Transaction successful, hash: ${transactionHash}`);
    } catch (error) {
        console.error('Error sending ETH:', error);
    }
}

const sendTransaction = async () => {
    try {
        // 请求获取以授权的账户
        const accounts = await window.ethereum.request({ method: 'eth_accounts' });
        const fromAddress = accounts[0];
        if (!fromAddress) {
            uni.showToast({ title: '请先连接钱包', icon: "none" });
            return;
        }
        txParams.form = fromAddress;
        openData.value = true
    } catch (error) {
        console.error('Error sending transaction:', error);
    }
}

const onSendEth = () => sendEth(txParams.form, txParams.to, Number(txParams.value))
</script>
<template>
    <view>
        <mButton @click="sendTransaction">向目标账户发送ETH</mButton>
        <mPopup v-model:open="openData" title="发送ETH">
            <view class="form-item">
                <view class="label">发送账户</view>
                <view class="input"><input type="text" v-model="txParams.form" disabled /></view>
            </view>
            <view class="form-item">
                <view class="label">目标账户</view>
                <view class="input"><input type="text" v-model="txParams.to" /></view>
            </view>
            <view class="form-item">
                <view class="label">发送数量</view>
                <view class="input"><input type="number" v-model="txParams.value" /></view>
            </view>
            <view class="bottoms">
                <mButton @click="openData = false">取消</mButton>
                <mButton @click="onSendEth">发送</mButton>
            </view>
        </mPopup>
    </view>
</template>

<style scoped lang="scss">
.form-item+.form-item {
    margin-top: 24rpx;
}

.bottoms {
    margin-top: 24rpx;
    display: flex;
    justify-content: space-between;
}
</style>